//
//  SN_NewspaperColection_ViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/6/23.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_NewspaperColection_ViewController.h"
#import "SN_NewspaperInfoViewController.h"

@protocol DeleteDelegate <NSObject>

- (void)deleteNewspaper:(UIButton *)btn;

@end

@interface SN_NewspaperCell : UICollectionViewCell

@property (nonatomic, strong) id<DeleteDelegate> delegate;
@property (nonatomic, strong) UIImageView *paperImg;
@property (nonatomic, strong) UIButton *deleteButton;

@end

@implementation SN_NewspaperCell

- (void)deleteNewspaper:(UIButton *)sender {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(deleteNewspaper:)]) {
        [self.delegate deleteNewspaper:sender];
    }
}

- (UIButton *)deleteButton {
    
    if (_deleteButton == nil) {
        
        _deleteButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_deleteButton setFrame:CGRectMake(75+9-50, 0, 50, 50)];
        [_deleteButton addTarget:self action:@selector(deleteNewspaper:) forControlEvents:(UIControlEventTouchUpInside)];
        [_deleteButton setImage:[UIImage imageNamed:@"newspaper_collection_del"] forState:(UIControlStateNormal)];
        _deleteButton.hidden = YES;
        [self.contentView addSubview:_deleteButton];
    }
    
    return _deleteButton;
}

- (UIImageView *)paperImg {
    
    if (_paperImg == nil) {
        _paperImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 9, 75, 100)];
        [self.contentView addSubview:_paperImg];
    }
    return _paperImg;
}



@end

@interface SN_NewspaperColection_ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DeleteDelegate>
{
    NSInteger pageNum;
    
    BOOL isEdit;
    
    UIButton *editBtn;
    
    UILabel *emptyLab;
}
@property (nonatomic, strong) UICollectionView *paperCollection;
@property (nonatomic, strong) NSMutableArray *paperArr;

@end

@implementation SN_NewspaperColection_ViewController

- (void)loadView {
    [super loadView];
    
    self.navBar.navigationItem.title = @"报纸收藏";
    [self.view setBackgroundColor:colorFromHex(@"ffffff")];
    
    editBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [editBtn setFrame:CGRectMake(0, 0, 44, 44)];
    [editBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [editBtn setTitle:@"编辑" forState:(UIControlStateNormal)];
    [editBtn setTitleColor:colorFromHex(@"ffffff") forState:(UIControlStateNormal)];
    [editBtn addTarget:self action:@selector(editAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
    
    [self.navBar.navigationItem setRightBarButtonItem:backItem];
    
    pageNum = 1;
    isEdit = NO;
    
    emptyLab = [[UILabel alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, 100)];
    [emptyLab setText:@"暂无数据"];
    [emptyLab setTextColor:colorFromHex(@"979797")];
    [emptyLab setTextAlignment:NSTextAlignmentCenter];
    emptyLab.center = self.view.center;
    emptyLab.font = [UIFont systemFontOfSize:15];
    emptyLab.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.view addSubview:self.paperCollection];
    
    [self.paperCollection addSubview:emptyLab];
    
    [self getCollectionData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Method

- (void)editAction {
    
    isEdit = !isEdit;
    [editBtn setTitle:isEdit?@"完成":@"编辑" forState:(UIControlStateNormal)];
    
    [self.paperCollection reloadData];
    
}

- (void)reloadCurrentData {
    
    [self.networkErrorView hideEmptyImage];
    [self getCollectionData];
    
}

#pragma mark -Request

- (void)getCollectionData {
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_newscollectionlist" forKey:@"method"];
    [param setObject:@"1" forKey:@"pageno"];
    [param setObject:@"20" forKey:@"pagesize"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dataDic = (NSDictionary *)jsonObject;
        
        NSArray *arr = [dataDic objectForKey:@"re_data"];
        
        self.paperCollection.hidden = NO;
        
        if (arr.count == 0) {
            
            emptyLab.hidden = NO;
            editBtn.hidden = YES;
            
            return;
        }
        editBtn.hidden = NO;
        self.paperArr = [[NSMutableArray alloc]init];
        
        for (NSDictionary *dic in arr) {
            SN_NewspaperModel *model = [SN_NewspaperModel mj_objectWithKeyValues:dic];
            [self.paperArr addObject:model];
        }
        [self.paperCollection reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        [self.networkErrorView showEmptyImage];
    }];
}

- (void)getMoreCollectionData {
    
    pageNum += 1;
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_newscollectionlist" forKey:@"method"];
    [param setObject:[NSString stringWithFormat:@"%ld",pageNum] forKey:@"pageno"];
    [param setObject:@"20" forKey:@"pagesize"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dataDic = (NSDictionary *)jsonObject;
        
        NSArray *arr = [dataDic objectForKey:@"re_data"];
        
        if (arr.count > 0) {
            for (NSDictionary *dic in arr) {
                SN_NewspaperModel *model = [SN_NewspaperModel mj_objectWithKeyValues:dic];
                [self.paperArr addObject:model];
            }
            
            [self.paperCollection reloadData];
        }else {
            pageNum -= 1;
        }
        
        [self.paperCollection.mj_footer endRefreshing];
        
    } failure:^(NSInteger recode, NSError *error) {
        pageNum -= 1;
    }];
}

#pragma mark - UICollectionDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.paperArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SN_NewspaperCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    
    cell.delegate = self;
    
    SN_NewspaperModel *paperModel = [self.paperArr objectAtIndex:indexPath.row];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%ld",IMAGEHOSTURL,paperModel.pic];
    [cell.paperImg sd_setImageWithURL:[NSURL URLWithString:urlStr]placeholderImage:[UIImage imageNamed:@"newspaper_default"]];
    
    cell.deleteButton.hidden = isEdit?NO:YES;
    
    return cell;
}

#pragma mark - UICollectionDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SN_NewspaperModel *paperModel = [self.paperArr objectAtIndex:indexPath.row];
    
    SN_NewspaperInfoViewController *infoVC = [[SN_NewspaperInfoViewController alloc]init];
    
    infoVC.paperModel = paperModel;
    
    [self.navigationController pushViewController:infoVC animated:YES];
    
}

- (void)deleteNewspaper:(UIButton *)sender {
    
    SN_NewspaperCell *cell = (SN_NewspaperCell *)[[sender superview] superview];//获取cell
    
    NSIndexPath *indexpath = [self.paperCollection indexPathForCell:cell];//获取cell对应的indexpath;
    
    //删除cell；
    SN_NewspaperModel *paperModel = [self.paperArr objectAtIndex:indexpath.row];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:@"api_szb_setnewscollection" forKey:@"Method"];
    [param setObject:[NSString stringWithFormat:@"%ld",paperModel.newid] forKey:@"newsid"];
    [param setObject:@"0" forKey:@"state"];
    [param setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:param showHUD:YES success:^(NSInteger recode, id jsonObject) {
        
        [self.paperArr removeObjectAtIndex:indexpath.row];
        [self.paperCollection deleteItemsAtIndexPaths:@[indexpath]];
        [self showHint:@"取消成功"];
        
        if (self.paperArr.count == 0) {
            editBtn.hidden = YES;
            emptyLab.hidden = NO;
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark - Get

- (UICollectionView *)paperCollection {
    
    if (_paperCollection == nil) {
        
        CGFloat itemWidth = 75+9;
        CGFloat itemHeight = 100;
        
        UICollectionViewFlowLayout *flowLayot = [[UICollectionViewFlowLayout alloc] init];
        flowLayot.sectionInset = UIEdgeInsetsZero;
        flowLayot.itemSize = CGSizeMake(itemWidth, itemHeight);
        flowLayot.minimumLineSpacing = 16;
        
        float space ;
        if (SCREENWIDTH == 320) {
            space = (SCREENWIDTH - 30+9 - itemWidth*3)/2.0;
        }else {
            space = (SCREENWIDTH - 30+9 - itemWidth*4)/3.0;
        }
        flowLayot.minimumInteritemSpacing = space;
        
        _paperCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(15, SafeAreaTopHeight+18-9, SCREENWIDTH-30+9, SCREENHEIGH- SafeAreaTopHeight - SafeAreaBottomHeight) collectionViewLayout:flowLayot];
        _paperCollection.delegate = self;
        _paperCollection.dataSource = self;
        [_paperCollection setBackgroundColor:[UIColor whiteColor]];
        [_paperCollection registerClass:[SN_NewspaperCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
        _paperCollection.hidden = YES;
        _paperCollection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self getMoreCollectionData];
        }];
        
    }
    
    return _paperCollection;
}

@end
